package com.dubbo.framework.protocol.dubbo;

import com.dubbo.framework.URL;
import com.dubbo.framework.config.ServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author by Mr. Li 2021/4/30 13:45
 */
@Slf4j
public class NettyServer {

    public void start(String ipAddr, int port) {

        log.info("netty server is running...");

        final NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            final ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            final ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder", new ObjectDecoder(ClassResolvers
                                    .weakCachingConcurrentResolver(this.getClass()
                                            .getClassLoader())))
                                    .addLast("encoder", new ObjectEncoder())
                                    .addLast(new NettyServerHandler());
                        }
                    });
            log.info("netty server start up， ip：{}，port：{}", ipAddr, port);
            final ChannelFuture channelFuture = bootstrap.bind(ipAddr, port).sync();
            //  将服务 服务注册到zk上
            ServerConfig.up(new URL(ipAddr, port));
            channelFuture.channel().closeFuture().sync(); // 这行必须 需要，不然阻塞到bind成功之后 就退出了，不会accept
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}
